package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.pojo.MallBoomPo;
import cc.linker.steplink.crm.merchant.service.MallBoomBackService;
import cc.linker.steplink.crm.merchanth5.controller.WxShareController;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.service.redis.SystemConfigService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("shop/mallboom")
public class MallBoomBackController {

    @Autowired
    private WxShareController wxShareController;
    @Autowired
    private MallBoomBackService mallBoomBackService;
    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private MallDao mallDao;

    @Autowired
    private HttpService httpService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /************************租户管理-资金账户配置*********************/

    /**
     * 获取下拉菜单
     */
    @GetMapping("/getselelist")
    public List getSeleList(){
        List<Map<String, String>> data = new ArrayList<>();
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("name","联汇资金子账户");
        param1.put("value","A");
        Map<String, String> param2 = new HashMap<String, String>();
        param2.put("name","联盟大麦资金账户");
        param2.put("value","B");
        data.add(param1);
        data.add(param2);
        return data;
    }

    /**
     * 获取当前配置
     */
    @GetMapping("/getorgaccountconf")
    public Map getOrgAccountConf(HttpServletRequest request) throws ParseException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, String> orgAccountConf = mallBoomBackService.getOrgAccountConf(orgId,"1");
        if(null == orgAccountConf){
            mallBoomBackService.addOrgAccountConf(orgId,"1");
        }
        Map<String, String> orgAccountConfDef = mallBoomBackService.getOrgAccountConf(orgId,"0");
        if(null == orgAccountConfDef){
            mallBoomBackService.addOrgAccountConf(orgId,"0");
        }
        Map<String, String> data = mallBoomBackService.getOrgAccountConf(orgId,"0");
        data.put("status","cancel");

        if(!StringUtils.isEmpty(data.get("changeTime"))){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String changeTime = formatter.format(data.get("changeTime"));
            if(!"1970-01-01".equals(changeTime)){
                data.put("status","doing");
            }else{
                data.put("changeTime","");
            }
        }

        return data;
    }

    /**
     * 保存配置
     */
    @PostMapping("/saveorgaccountconf")
    public Boolean saveOrgAccountConf(@RequestBody Map<String, String> map) throws GlobalException {
        if(StringUtils.isEmpty(map.get("orgId"))){
            throw GlobalException.build("参数错误");
        }

        Map<String, String> orgAccountConf = mallBoomBackService.getOrgAccountConf(map.get("orgId"),"0");
        if(null == orgAccountConf){
            throw GlobalException.build("非法操作");
        }
        if(StringUtils.isEmpty(map.get("changeTime"))){
            throw GlobalException.build("参数错误");
        }
        Map<String, String> param = new HashMap<String, String>();
        param.put("orgId",map.get("orgId"));
        param.put("account_a",map.get("accountMarket"));
        param.put("account_b",map.get("accountServe"));
        param.put("account_c",map.get("accountFund"));
        param.put("changeTime",map.get("changeTime"));
        return mallBoomBackService.saveOrgAccountConf(param);
    }


    /**
     * 取消变更
     */
    @PostMapping("/cancelorgaccountconf")
    public Boolean cancelOrgAccountConf(HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return mallBoomBackService.cancelOrgAccountConf(userinfo.getOrgId());
    }


    /************************租户管理-资金账户配置*********************/





    @Value("${system.scrm.sync.contentUrl}")
    private String synccontentUrl;

    @GetMapping("/getlimitqrcode")
    public Map getLimitQrcode(@RequestParam(value = "pCustomerId", defaultValue = "", required = false) String pCustomerId,
                              HttpServletRequest request) throws Exception {
        String token = this.mallBoomDao.getTokenByCustomerId(pCustomerId);
        if (StringUtils.isEmpty(token)) {
            throw GlobalException.build("仅关注公众号的联盟商家用户可以调用此接口");
        }
        return wxShareController.getLimitQrcodeInfo(token, pCustomerId);
    }

    /**
     * 获取麦爆啦设置
     *
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/getset")
    public MallBoomPo getSet(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return mallBoomBackService.getSet(userinfo.getOrgId());
    }

    /**
     * 配置麦爆啦
     *
     * @param map
     * @param session
     * @throws Exception
     */
    @PostMapping("/set")
    public void setMall(@RequestBody Map<String, Object> map, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<String, Object>();
        if (map.containsKey("freezeTime")) {
            params.put("freezeTime", map.get("freezeTime").toString());
        } else {
            params.put("freezeTime", 30);
        }
        if (map.containsKey("amount")) {
            params.put("amount", Integer.parseInt(map.get("amount").toString()) * 100);
        } else {
            params.put("amount", 0);
        }
        if (map.containsKey("rebate")) {
            params.put("rebate", Integer.parseInt(map.get("rebate").toString()));
        } else {
            params.put("rebate", 0);
        }
        if (map.containsKey("recommend")) {
            params.put("recommend", Integer.parseInt(map.get("recommend").toString()));
        } else {
            params.put("recommend", 0);
        }
        if (map.containsKey("seniorAmount")) {
            params.put("seniorAmount", Integer.parseInt(map.get("seniorAmount").toString()) * 100);
        } else {
            params.put("seniorAmount", 0);
        }
        if (map.containsKey("seniorRebate")) {
            params.put("seniorRebate", Integer.parseInt(map.get("seniorRebate").toString()));
        } else {
            params.put("seniorRebate", 0);
        }
        if (map.containsKey("serviceRatio")) {
            params.put("serviceRatio", Integer.parseInt(map.get("serviceRatio").toString()));
        } else {
            params.put("serviceRatio", 50);
        }


        params.put("agentCheck", map.get("agentCheck"));
        params.put("promoterCheck", map.get("promoterCheck"));
        // 未产生费用 1 给商家 2 给平台
        params.put("unhappen", map.containsKey("unhappen") ? Integer.parseInt(map.get("unhappen").toString()) : 1);


        // 商品服务费比例
        params.put("serviceRatio", map.containsKey("serviceRatio") ? Integer.parseInt(map.get("serviceRatio").toString()) : 0);
        // 商品推荐费占商品总返润比例
        params.put("recommendRatio", map.containsKey("recommendRatio") ? Integer.parseInt(map.get("recommendRatio").toString()) : 0);
        // 平台抽成比例
        params.put("platformRatio", map.containsKey("platformRatio") ? Integer.parseInt(map.get("platformRatio").toString()) : 0);
        // 原创抽成比例
        params.put("originalRatio", map.containsKey("originalRatio") ? Integer.parseInt(map.get("originalRatio").toString()) : 0);

        if (Integer.parseInt(params.get("serviceRatio").toString()) + Integer.parseInt(params.get("recommendRatio").toString()) +
                Integer.parseInt(params.get("platformRatio").toString()) + Integer.parseInt(params.get("originalRatio").toString()) != 100) {
            throw new GlobalException(new ResponseException(400, "返润设置中费用比例相加必须等于100.0%"));
        }

        Integer salerPromoter = (Integer) map.get("salerPromoter");
        if (null == salerPromoter) {
            salerPromoter = 0;
        }
        if (salerPromoter != 0 && salerPromoter != 1) {
            throw GlobalException.build("参数错误");
        }
        params.put("salerPromoter", salerPromoter);

        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        int i = mallBoomBackService.setMall(params);
        if (i < 1) {
            throw new GlobalException(new ResponseException(400, "设置失败"));
        }

        // 先删除 生成缓存
        stringRedisTemplate.delete(SystemConfigService.ORG_SET_INFO_KEY + orgId);
        stringRedisTemplate.opsForValue().set(SystemConfigService.ORG_SET_INFO_KEY + orgId, JSON.toJSONString(params, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 商家列表
     *
     * @param session
     * @param pageIndex
     * @param pageSize
     * @return
     * @throws Exception
     */
    @GetMapping("/getsales")
    public Object getSales(HttpServletRequest request,
                           @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                           @RequestParam(value = "storeName", required = false) String storeName,
                           @RequestParam(value = "customerPhone", required = false) String customerPhone,
                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String ,Object> params = new HashMap<>();
        params.put("orgId",orgId);
        Integer payMode = mallDao.getPayModeByOrgId(params);
        if (payMode == null) {
            payMode = 1;
        }
        params.put("payMode",payMode);
        params.put("storeName",storeName);
        params.put("customerPhone",customerPhone);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(mallBoomBackService.getSales(params));
    }

    /**
     * 获取当前机构推荐的麦爆成员
     *
     * @param session
     * @return
     */
    @PostMapping("/getsonboomlist")
    @ResponseBody
    public Object getSonBoomList(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        List<Map<String, String>> sonList = mallBoomBackService.getSonBoomList(userinfo.getOrgId());
        Map<String, Object> data = new HashMap<>();
        data.put("count", sonList.size());
        data.put("sonList", sonList);
        return data;
    }

    /**
     * 修改商品最大上传数量
     *
     * @param session
     * @param map
     */
    @PostMapping("/updategoodsmax")
    public void updateGoodsMax(
            HttpServletRequest request,
            @RequestBody Map<String, Object> map) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<String, Object>();
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        if (!map.containsKey("customerId")) {
            throw GlobalException.build("参数错误");
        }
        if (!map.containsKey("goodsMax")) {
            throw GlobalException.build("参数错误");
//            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        params.put("customerId", map.get("customerId").toString());
        params.put("goodsMax", map.get("goodsMax").toString());

        mallBoomBackService.updateGoodsMax(params);

    }

    /**
     * 暂停
     *
     * @param session
     * @param map
     */
    @PostMapping("/suspend")
    public void suspend(
            HttpServletRequest request,
            @RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        if (!map.containsKey("customerId")) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        params.put("customerId", map.get("customerId").toString());
        mallBoomBackService.suspend(params);

    }

    /**
     * 恢复
     *
     * @param session
     * @param map
     */
    @PostMapping("/recovery")
    public void recovery(
            HttpServletRequest request,
            @RequestBody Map<String, Object> map) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<String, Object>();
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        if (!map.containsKey("customerId")) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        params.put("customerId", map.get("customerId").toString());
        mallBoomBackService.recovery(params);
    }

    /**
     * 查看资质详情 用户id
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/getsalerverify")
    public Map<String, Object> getSalerVerify(
            @RequestParam(value = "customerId") String customerId) throws Exception {
        return mallBoomBackService.getSalerVerify(customerId);
    }

    /**
     * 资质审核列表
     *
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/salerverifylist")
    public Object salerVerifyList(
            HttpServletRequest request,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize) throws Exception {
        PageHelper.startPage(pageIndex, pageSize);
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return new PageInfo<>(mallBoomBackService.salerVerifyList(userinfo.getOrgId()));
    }

    /**
     * 查看资质详情 用户id
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/getsalerverifybyid")
    public Map<String, Object> getSalerVerifyById(
            @RequestParam(value = "id") int id) throws Exception {
        return mallBoomBackService.getSalerVerifyById(id);
    }

    /**
     * 审核操作
     *
     * @param map
     * @throws Exception
     */
    @PostMapping("/doverify")
    public void doVerify(
            @RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        if (!map.containsKey("status")) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        if (!map.containsKey("id")) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        if (!map.containsKey("customerId")) {
            throw new GlobalException(new ResponseException(400, "参数错误"));
        }
        params.put("status", map.get("status").toString());
        params.put("id", map.get("id").toString());
        params.put("customerId", map.get("customerId").toString());
        mallBoomBackService.doVerify(params);
    }


    /**
     * 获取当前用户的文章列表
     *
     * @param pageIndex
     * @param pageSize
     * @param session
     * @return
     * @throws IOException
     * @throws URISyntaxException
     * @throws GlobalException
     */
    @GetMapping("/getuserarticlelist")
    public Map getUserArticleList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                  @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                  HttpServletRequest request) throws GlobalException, IOException, URISyntaxException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String casUserId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();

        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_LIST;
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> resData = new HashMap<String, Object>();
        param.put("userId", casUserId);
        param.put("orgId", orgId);
        param.put("pageSize", pageSize);
        if ((pageIndex - 1) < 0) {
            pageIndex = 1;
        }
        param.put("pn", pageIndex - 1);


        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
        String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        if (null != postres) {
            Map res = (Map) JSON.parse(postres);
            if ("200".equals(res.get("code").toString())) {
                resData = (Map) res.get("data");
            } else {
                throw GlobalException.build("请求失败");
            }
        } else {
            throw GlobalException.build("请求失败");
        }
        return resData;
    }

    /**
     * 关系查询
     */
//    @GetMapping("/getuserlist")
//    public Object getUserList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
//                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
//                              @RequestParam(value = "user", defaultValue = "", required = false) String user,
//                              @RequestParam(value = "parent", defaultValue = "", required = false) String parent,
//                              HttpSession session) {
//
//        String orgId = userinfo.getOrgId();
//        PageHelper.startPage(pageIndex, pageSize);
//
//        Map<String, String> param = new HashMap<String, String>();
//        param.put("orgId", orgId);
//
//        List<Map<String, String>> allUserList = mallBoomBackService.getAllUserList(param);
//        //只搜用户
//        if (!"".equals(user) && "".equals(parent)) {
//            param.put("user", user);
//            allUserList = mallBoomBackService.getUserList(param);
//        }
//        //只搜上级
//        if ("".equals(user) && !"".equals(parent)) {
//            param.put("parent", parent);
//            allUserList = mallBoomBackService.getParentList(param);
//        }
//        //同时搜索
//        if (!"".equals(user) && !"".equals(parent)) {
//            param.put("parent", parent);
//            param.put("user", user);
//            allUserList = mallBoomBackService.getUserParentList(param);
//        }
//
//        for (Map<String, String> item : allUserList) {
//            if (null == item.get("pName") && (null == item.get("pPhone") || "".equals(item.get("pPhone")))) {
//                item.put("pName", "平台");
//                item.put("pPhone", "-");
//            }
//            if (null == item.get("saveTime")) {
//                item.put("saveTime", "-");
//            }
//            Map<String, String> salerParam = new HashMap<String, String>();
//            salerParam.put("orgId", item.get("corgId"));
//            salerParam.put("customerId", item.get("ccustomerId"));
//            Integer salerCount = mallBoomBackService.getSalerCount(salerParam);
//            if (salerCount > 0) {
//                item.put("cUserType", "联盟商家");
//            } else {
//                if ("promoter".equals(item.get("cUserType"))) {
//                    item.put("cUserType", "加盟代理");
//                } else {
//                    item.put("cUserType", "推广员");
//                }
//            }
//        }
//        return new PageInfo<>(allUserList);
//    }

    /**
     * 小b配标签和备注
     *
     * @param customerId 用户id
     * @param labelIds   标签id，逗号
     * @param desc       备注
     */
    @PostMapping("/labelremark")
    public void labelingAndRemarks(@RequestBody Map<String, Object> map) throws GlobalException {
        if (!map.containsKey("customerId") || !map.containsKey("labelIds") || !map.containsKey("desc")) {
            throw GlobalException.build("信息缺失");
        }
        mallBoomBackService.updateSalerLabelAndRemark(map);
    }
}
